
<template>
  <material-card
    color="primary"
  >
    <template
      v-if="titleSwitch"
      #title
    >
      <v-row>
        <small class="text-h4">{{ title }}</small>
        <v-btn
          class="mx-0"
          fab
          icon
          x-small
          color="primary"
          @click="refleshX()"
        >
          <v-icon>mdi-cached</v-icon>
        </v-btn>
      </v-row>
    </template>
    <v-row>
      <v-col
        cols="12"
        md="10"
      >
        <div :id="divID" />
      </v-col>
      <v-col
        cols="12"
        md="2"
      >
        <v-card>
          <v-alert
            type="success"
            dense
          >
            {{ s }}
          </v-alert>
          <v-card-text>
            <span class="mr-12">{{ lanChar.deviceInfo }}</span><br>
            <v-divider />
            <span class="mr-2">{{ lanChar.deviceName }}:<i>{{ info.name }}</i><br></span>
            <span class="mr-2">{{ lanChar.deviceID }}:<i>{{ info.id }}</i><br></span>
            <span class="mr-2">{{ lanChar.deviceType }}:<i>{{ info.devType }}</i><br></span>
            <span
              v-if="info.devType==='MC-Group'"
              class="mr-2"
            >{{ lanChar.accessPointer }}:<i>{{ info.ap }}</i><br></span>
            <span
              v-if="info.devType==='MC-Group'"
              class="mr-2"
            >{{ lanChar.terminalNum }}:<i>{{ info.tNum }}</i><br></span>
            <span
              v-if="info.devType==='E-Gateway'"
              class="mr-2"
            >{{ lanChar.groupNum }}:<i>{{ info.gNum }}</i><br></span>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </material-card>
</template>

<script>
  import globalDef from '@/util/globals'
  import lan from '@/util/lan-char'
  import G6 from '@antv/g6'
  import insertCss from 'insert-css'
  import * as mcAxios from '@/util/mcaxios'
  import topo from './topo'

  export default {
    name: 'TopView',
    props: {
      titleSwitch: {
        type: Boolean,
        required: false,
        default: true,
      },
      title: String,
      divID: {
        type: String,
        required: false,
        default: 'g-apptpl-topview',
      },
      subView: {
        type: Object,
        required: false,
        default: function () {
          return {
            groupView: 0,
            gwID: '',
            groupID: '',
          }
        },
      },
    },
    data: () => ({
      lanChar: lan.GetLan(),
      alertType: 'success',
      groupInfo: [
        {
          GroupName: 'group-xx-1',
          TcpServerInfo: {
            Uris: [
              { Uri: 'tcp://ip-address/port' },
            ],
            ConnectionNum: 10,
          },
          UdpServerInfo: {
            Uris: [
              { Uri: 'udp://ip-address/port' },
            ],
            ConnectionNum: 10,
          },
          TerminalInfo: {
            Uris: [
              { Uri: 'udp://ip-address/port1' },
              { Uri: 'udp://ip-address/port2' },
              { Uri: 'udp://ip-address/port3' },
              { Uri: 'udp://ip-address/port4' },
              { Uri: 'udp://ip-address/port5' },
              { Uri: 'tcp://ip-address/port1' },
              { Uri: 'tcp://ip-address/port2' },
              { Uri: 'tcp://ip-address/port3' },
              { Uri: 'tcp://ip-address/port4' },
              { Uri: 'tcp://ip-address/port5' },
            ],
            ConnectionNum: 10,
          },
        },
        {
          GroupName: 'group-xx-2',
          TcpServerInfo: {
            Uris: [
              { Uri: 'tcp://ip-address/port' },
            ],
            ConnectionNum: 10,
          },
          UdpServerInfo: {
            Uris: [
              { Uri: 'udp://ip-address/port' },
            ],
            ConnectionNum: 10,
          },
          TerminalInfo: {
            Uris: [
              { Uri: 'udp://ip-address/port1' },
              { Uri: 'udp://ip-address/port2' },
              { Uri: 'udp://ip-address/port3' },
              { Uri: 'udp://ip-address/port4' },
              { Uri: 'udp://ip-address/port5' },
              { Uri: 'tcp://ip-address/port1' },
              { Uri: 'tcp://ip-address/port2' },
              { Uri: 'tcp://ip-address/port3' },
              { Uri: 'tcp://ip-address/port4' },
              { Uri: 'tcp://ip-address/port5' },
            ],
            ConnectionNum: 10,
          },
        },
      ],
      topInfo: {
        id: 'Center-Gateway',
        name: '中心网关',
        devType: 'C-Gateway',
        gws: [
          {
            id: 'Edge-Gateway-0',
            name: '边缘网关-0',
            devType: 'E-Gateway',
            groupInfo: [],
          },
        ],
      },
      info: { name: '', id: '', devType: '', ap: '', tNum: 0, gNum: 0 },
      s: lan.LanChar.deviceOK,
      graphXG6: null,
    }),
    computed: {
    },
    watch: {
    },
    created () {
      globalDef.VueObject.$on('lanChange', lanChar => {
        this.lanChar = lanChar
      })

      insertCss(`
        .g-x-tooltip {
          border-radius: 6px;
          font-size: 16px;
          text-align: left;
        }
      `)
    },
    mounted () {
      // this.graphXG6Init()
      this.initRenderTopoInfo()
    },
    beforeDestroy () {
    },
    methods: {
      graphXG6Init () {
        const container = document.getElementById(this.divID)
        const width = container.scrollWidth
        // const height = container.scrollHeight || 500
        const height = screen.availHeight

        const tooltip = new G6.Tooltip({
          // offsetX and offsetY include the padding of the parent container
          offsetX: 10,
          offsetY: 10,
          // the types of items that allow the tooltip show up
          // 允许出现 tooltip 的 item 类型
          itemTypes: ['node'],
          // custom the tooltip's content
          // 自定义 tooltip 内容
          getContent: (e) => {
            const outDiv = document.createElement('div')
            const model = e.item.getModel()

            if (model.devType === 'E-Gateway') {
              this.info.name = model.info.name
              this.info.id = model.info.id
              this.info.devType = model.info.devType
              this.info.gNum = model.children.length
            }
            if (model.devType === 'MC-Group') {
              this.info.name = model.info.GroupName
              this.info.id = model.id
              this.info.devType = model.devType
              this.info.ap = ''
              for (var tcpUri of model.info.TcpServerInfo.Uris) {
                this.info.ap += (tcpUri.Uri + ';')
              }
              for (var udpUri of model.info.UdpServerInfo.Uris) {
                this.info.ap += (udpUri.Uri + ';')
              }
              this.info.tNum = model.info.TerminalInfo.ConnectionNum
            }

            var tmpl = `${this.lanChar.deviceName}:${model.label}</br>${this.lanChar.deviceID}:${model.id}`
            if (model.devType === 'MC-Group' || model.devType === 'E-Gateway') {
              tmpl = `${this.lanChar.deviceName}:${model.label}</br>${this.lanChar.description}:${model.description}`
            }
            outDiv.style.width = 'fit-content'
            outDiv.style.padding = '0px 0px 20px 0px'
            outDiv.innerHTML = `<div class="g-x-tooltip">${tmpl}</div>`
            return outDiv
          },
        })

        const graph = new G6.TreeGraph({
          container: this.divID,
          width,
          height,
          fitView: true,
          fitViewPadding: 10,
          linkCenter: true,
          modes: {
            default: [
              // {
              //   type: 'collapse-expand',
              //   onChange: function onChange (item, collapsed) {
              //     const data = item.get('model')
              //     data.collapsed = collapsed
              //     return true
              //   }
              // },
              'drag-canvas',
              'zoom-canvas',
            ],
          },
          defaultNode: topo.defaultNode,
          defaultEdge: topo.defaultEdge,
          nodeStateStyles: topo.nodeStateStyles,
          layout: {
            type: 'mindmap',
            direction: 'H',
            getHeight: () => {
              return 16
            },
            getWidth: () => {
              return 16
            },
            getVGap: () => {
              return 10
            },
            getHGap: () => {
              return 50
            },
            getSide: (d) => {
              if (d.id === 'Edge Gateway1') {
                return 'left'
              }
              return 'right'
            },
          },
          plugins: [tooltip],
        })

        // let centerX = 0
        graph.node(function (node) {
          // if (node.devType === 'C-Gateway') {
          //   centerX = node.x
          // }

          // if (node.devType === 'MC-Group' || node.devType === 'Terminal') {
          //   return {
          //     labelCfg: {
          //       position:
          //         node.children && node.children.length > 0
          //           ? 'left'
          //           : node.x > centerX
          //             ? 'right'
          //             : 'left',
          //       offset: 5,
          //     },
          //   }
          // } else {
          //   return {
          //     labelCfg: {
          //       position: 'center',
          //     },
          //   }
          // }
          return {
            labelCfg: {
              position: 'center',
            },
          }
        })

        var data = topo.xTopData
        this.graphXG6 = graph
        graph.data(data)
        graph.render()
        graph.fitView()

        graph.on('node:mouseenter', (e) => {
          const { item } = e
          graph.setItemState(item, 'hover', true)
        })
        graph.on('node:mouseleave', (e) => {
          const { item } = e
          graph.setItemState(item, 'hover', false)
        })
        const subView = this.subView
        const router = this.$router
        graph.on('node:click', function (e) {
          const node = e.item
          const model = node.getModel()

          if (model.devType === 'MC-Group') {
            subView.gwID = model.gwID
            subView.groupID = model.id
            subView.groupView++
          }

          if (model.devType === 'E-Gateway') {
            router.replace('apptpl/status')
          }
        })

        if (typeof window !== 'undefined') {
          window.onresize = () => {
            if (!graph || graph.get('destroyed')) return
            if (!container || !container.scrollWidth || !container.scrollHeight) return
            graph.changeSize(container.scrollWidth, container.scrollHeight)
          }
        }
      },
      async getMcGroupsInfo () {
        const data = {
          request_type: 'mc groups info get',
          instance_id: 'instance_id',
          sequence_no: 1000,
        }
        return mcAxios.axiosGetConfig(data)
      },
      async initRenderTopoInfo () {
        try {
          const res = await this.getMcGroupsInfo()
          if (res.data.status === true) {
            this.groupInfo = []
            res.data.data.forEach((element, index) => {
              this.groupInfo[index] = element
            })

            topo.initTopData()
            topo.addCenterGw(this.topInfo)
            for (var gw of this.topInfo.gws) {
              const topoGW = topo.addEdgeGw(gw)
              //     for (var group of gw.groupInfo) {
              for (var group of this.groupInfo) {
                topo.addGroupToGw(topoGW, group)
                group.topoGw = topoGW
              }
            }

            this.graphXG6Init()
          } else {
            console.log('getMcGroupsInfo get res fail')
          }
        } catch (e) {
          console.log('getMcGroupsInfo get fail: ', e)
        }
      },
      chartUpdate () {
        this.graphXG6.data(topo.xTopData)
        this.graphXG6.render()
      },
      refleshX () {
        this.chartUpdate()
      },
    },
  }
</script>
